package com.code.monitor.controller;

import com.code.monitor.annotation.Controller;
import com.code.monitor.annotation.RequestMapping;
import com.code.monitor.annotation.RequestParam;
import com.code.monitor.annotation.ResponseBody;
import com.code.monitor.constants.ResultEntity;
import com.code.monitor.model.MachineInfo;
import com.code.monitor.service.MachineService;
import com.code.monitor.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * @author ggh
 * @date 2023/5/8
 */
@Controller
@Slf4j
public class MachineController {

    public static final int IP_DETECTION_TIMEOUT = 5000;
    public static final int SHUTDOWN_TIMEOUT = 5000;

    /**
     * 查询机器列表信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list")
    public ResultEntity list() {
        try {
            return ResultEntity.success(SpringUtils.getBean(MachineService.class).queryAllMachine());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultEntity.fail("查询失败");
    }

    /**
     * 添加机器信息
     *
     * @param ip
     * @param username
     * @param password
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addMachine")
    public ResultEntity addMachine(@RequestParam("ip") String ip, @RequestParam("sshPort") Integer sshPort, @RequestParam("username") String username, @RequestParam("password") String password,
                                   @RequestParam("sftpRoot") String sftpRoot, @RequestParam("packagejar") String packagejar) {
        try {
            log.info("添加机器信息:{}", ip, username, password);
            MachineInfo machineInfo = new MachineInfo();
            machineInfo.setIp(ip);
            machineInfo.setSshPort(sshPort);
            machineInfo.setUsername(username);
            machineInfo.setPassword(password);
            machineInfo.setSftpRoot(sftpRoot);
            machineInfo.setPackagejar(packagejar);
            machineInfo.setAddTime(new Date());
            SpringUtils.getBean(MachineService.class).addMachineInfo(machineInfo);
            return ResultEntity.success("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultEntity.fail("操作失败");
    }

    /**
     * 添加机器信息
     *
     * @param ip
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delMachine")
    public ResultEntity delMachine(@RequestParam("ip") String ip) {
        try {
            log.info("删除机器信息:{}", ip);
            SpringUtils.getBean(MachineService.class).delMachineInfo(ip);
            return ResultEntity.success("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultEntity.fail("操作失败");
    }
}
